package com.lq.filestudy.utils;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import org.springframework.stereotype.Component;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
@Component
public class EasyExcelUtil<T> {
    private List<Map<Integer, String>> dataList = new ArrayList<>();
    private List<T> dataEntityList = new ArrayList<>();

    /** 根据文件路径读取表格文件
     * @param filePath 文件路径
     * @param headRowNumber 读取行数 0代表从第一行开始读取
     * @return List<Map<Integer, String>>
     */
    public List<Map<Integer, String>> excelReadFilePath(String filePath, Integer headRowNumber) {
        ExcelDataListener listener = new ExcelDataListener();
        EasyExcel.read(filePath).sheet().registerReadListener(listener).headRowNumber(headRowNumber).doRead();
        return dataList.subList(0,10);
    }

    /**
     * 根据文件对象读取表格文件
     * @param file 文件对象
     * @param headRowNumber 读取行数 0代表从第一行开始读取
     * @return List<Map<Integer, String>>
     */
    public List<Map<Integer, String>> excelReadFile(File file, Integer headRowNumber) {
        ExcelDataListener listener = new ExcelDataListener();
        EasyExcel.read(file).sheet().registerReadListener(listener).headRowNumber(headRowNumber).doRead();
        return dataList;
    }

    /**
     * 根据文件路径读取表格文件，实体类映射
     * 实体类需要使用注解  @ExcelProperty("对应表格列名")
     *                  @ExcelIgnore 忽略字段
     * @param filePath  文件路径
     * @param headRowNumber 读取行数 0代表从第一行开始读取
     * @param t 对应实体类
     * @return List<T>
     */
    public List<T> excelReadFilePathByEntity(String filePath, Integer headRowNumber, Class<T> t) {
        EasyExcel.read(filePath, t, new ExcelDataEntityListener()).sheet().headRowNumber(headRowNumber).doRead();
        return dataEntityList;
    }

    /**
     *
     * @param file 文件对象
     * @param headRowNumber 读取行数 0代表从第一行开始读取
     * @param t 对应实体类
     * @return List<T>
     */
    public List<T> excelReadFileByEntity(File file, Integer headRowNumber, T t) {
        EasyExcel.read(file, (Class) t, new ExcelDataEntityListener()).sheet().headRowNumber(headRowNumber).doRead();
        return dataEntityList;
    }

    /**
     * 监听每一行数据
     */
    class ExcelDataEntityListener extends AnalysisEventListener<T> {

        @Override
        public void invoke(T t, AnalysisContext analysisContext) {
            dataEntityList.add(t);
        }

        @Override
        public void doAfterAllAnalysed(AnalysisContext analysisContext) {
            dataEntityList.forEach(System.out::println);
        }
    }

    /**
     * 监听数据
     */
    class ExcelDataListener extends AnalysisEventListener<Map<Integer, String>> {

        @Override
        public void invoke(Map<Integer, String> rowData, AnalysisContext analysisContext) {
            //处理读取的每一行数据，rowData为包含一行Excel数据的map集合
            dataList.add(rowData);
        }

        @Override
        public void doAfterAllAnalysed(AnalysisContext analysisContext) {
            /*dataList.forEach(map->map.forEach((index,value)->{
                System.out.println(index+"--->"+value);//数据打印
            }));*/
        }
    }

    /**
     * 写入数据到Excel表格，并下载到浏览器
     * 入参第一个List为行，0代表第一行，第二个List每一列数据
     * 需保证标题列与数列对应，防止数错行
     * @param response 响应流
     * @param fileName 下载到浏览器的文件名
     * @param sheetName sheet页名
     * @param header 标题行
     * @param data 每一行数据
     * @throws IOException
     */
    public void writeFileToBrowser(HttpServletResponse response, String fileName, String sheetName, List<List<String>> header, List<List<String>> data) throws IOException {
        response.setHeader("Content-Transfer-Encoding", "binary'");
        response.setHeader("'Cache-Control", "must-revalidate,post-check=0,pre-check=0");
        response.setHeader("Pragma", "public");
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset-UTF-8");
        fileName = URLEncoder.encode(fileName, "UTF-8");//解决中文乱码
        String header_body = "inline; filename=" + fileName + "; filename*=utf-8" + fileName;
        response.setHeader("Content-Disposition", header_body);
        EasyExcel.write(response.getOutputStream())
                .head(header)
                .autoCloseStream(Boolean.FALSE)
                .sheet(sheetName)
                .doWrite(data);
    }

    /**
     * 写入数据到Excel表格，并下载到浏览器
     * 需有对应实体类
     *
     * @param response 响应流
     * @param fileName 下载到浏览器的文件名
     * @param sheetName sheet页名
     * @param header 标题行对应实体类
     * @param data 每一行数据 实体类集合
     * @throws IOException
     */
    public void writeFileToBrowserByEntity(HttpServletResponse response, String fileName, String sheetName, Class<T> header, List<T> data) throws IOException {
        response.setHeader("Content-Transfer-Encoding", "binary'");
        response.setHeader("'Cache-Control", "must-revalidate,post-check=0,pre-check=0");
        response.setHeader("Pragma", "public");
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset-UTF-8");
        fileName = URLEncoder.encode(fileName, "UTF-8");//解决中文乱码
        String header_body = "inline; filename=" + fileName + "; filename*=utf-8" + fileName;
        response.setHeader("Content-Disposition", header_body);
        EasyExcel.write(response.getOutputStream(),header)
                .head((Class) header)
                .autoCloseStream(Boolean.FALSE)
                .sheet(sheetName)
                .doWrite(data);
    }
}

